package controllers;
 
import java.util.List;

import javax.persistence.*;
import models.*;
import play.data.Form;
import play.mvc.*;
import views.html.*;
 
public class Users extends Controller {
 
	static play.data.Form<User> userForm = form(User.class);
	static Form<User> useForm = userForm.bindFromRequest();

 
	public static Result users() {
		return ok(
				user.render(null,User.all()));
	}
	
    public static Result add(Long id) {
    	Form<User> filledForm = userForm.bindFromRequest();
    	if(filledForm.hasErrors()) {
			flash("error","OOOooops!!! Remplir les champs manquants.");
			return badRequest(
					views.html.user.render(id,filledForm));
		}else { // <--- on n'enregistre que si tout va bien
			User _user = userForm.bindFromRequest().get();
			if(_user.findById(id)==null){
				User.create(_user);
				flash("success", "Login ### "
						+ filledForm.get().login + " ### has been created");
			}	
			else{
				flash("error", "Login ### "
						+ filledForm.get().login + " ### already exist");
			}
			return redirect(routes.Users.users());
		}
    }
    
    /*public static void delete(String login) {
        User.delete(login);
        return redirect(routes.Users.users());
    }
    */
	public static User findByName(String login){
		return User.findByLogin(login);
	}
	
	public static Result delete(Long id) {
		User.delete(id);
		return redirect(routes.Users.users());  
	}
	
}